/*
 * Copyright (C) 2020 Jimmy Hogoboom
 *
 * This file is part of Limitlist.
 *
 * Limitlist is free software: you can redistribute it and/or modify
 * it under the terms of the Affero GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Limitlist is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * Affero GNU General Public License for more details.
 *
 * You should have received a copy of the Affero GNU General Public License
 * along with Limitlist.  If not, see <https://www.gnu.org/licenses/>.
 */

// SPDX-License-Identifier: AGPL-3.0-or-later

import React, { ChangeEvent } from 'react';
import MaskedInput, { MaskedInputProps } from 'react-text-mask';
import createNumberMask from 'text-mask-addons/dist/createNumberMask';

interface CurrencyInputProps {
  value: any,
  onChange?: (e: ChangeEvent<HTMLInputElement>) => void,
}

const CurrencyInput: React.FC<CurrencyInputProps & MaskedInputProps> = (props) => {
  // More info here: https://www.nicknish.co/blog/react-currency-input
  // and https://codesandbox.io/embed/react-currency-input-with-react-text-mask-4es23
  const currencyMask = {
    prefix: '$',
    suffix: '',
    includeThousandsSeparator: true,
    thousandsSeparatorSymbol: ',',
    allowDecimal: true,
    decimalSymbol: '.',
    decimalLimit: 2,
    integerLimit: 7,
    allowNegative: false,
    allowLeadingZeroes: false,
  };

  return (
    <MaskedInput
      type="text"
      mask={createNumberMask(currencyMask)}
      inputMode="decimal"
      value={props.value}
      { ...props }
    />
  );
};

export default CurrencyInput;
